package it.ap.sa.acqua.login.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import it.ap.sa.acqua.auth.security.CustomUserDetailsService;
import it.ap.sa.acqua.auth.service.UserService;
import it.ap.sa.acqua.dao.beans.TUserBean;
import it.ap.sa.acqua.shared.web.AbstractCtrl;
import it.ap.sa.core.dao.beans.search.ResponseData;
import it.ap.sa.core.utils.LogUtil;

@Controller(value = "User Controller")
@RequestMapping("/userCtrl")
public class UserCtrl extends AbstractCtrl {

	/**
	 * logger
	 */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CustomUserDetailsService customUserDetailsService;
	
	@Override
	@RequestMapping(value = "/userDetail")
	public ModelAndView loadPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String    idLog     = "loadPage";
		StopWatch stopWatch = LogUtil.startStopWatch(idLog);
		logger.info("Start " + idLog);
		try{
			ModelAndView  mav      		= new ModelAndView(this.getPathPages() + "userDetail");
			return mav;
		}finally{
			logger.info(LogUtil.endStopWatch(stopWatch));
		}
	}
	
	/**
	 * Restituisce l'utente in sessione 
	 */
	@RequestMapping(value = "/getUser.pjson", method = {RequestMethod.POST,RequestMethod.GET})
	public @ResponseBody ResponseData getUser(HttpServletRequest request) {
		ResponseData response = new ResponseData();
		try {
			
			response.setAaData( this.customUserDetailsService.getPrincipal() );			
			response.setSuccess(true);
		} catch (Exception e) {
			logger.error("Error in getUser", e);
			response.setSuccess(false);
		}
		return response;
	}
	
	/**
	 */
	@RequestMapping(value = "/saveUser.pjson",method = {RequestMethod.POST,RequestMethod.GET})
	public @ResponseBody ResponseData saveUser(HttpServletRequest request, 
			@RequestBody TUserBean tUserBean ) throws Exception {
		
		ResponseData response = new ResponseData();
		try {
			userService.updateUser( tUserBean );
			response.setSuccess(true);
		} catch (Exception e) {
			logger.error("Error in saveUser", e);
			response.setSuccess(false);
		}
		return response;
	}
}
